package com.peter.demo_04;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		ByteBuffer buf = ByteBuffer.allocate(1024);

		System.out.println(buf.position());

		System.out.println(buf.limit());

		System.out.println(buf.capacity());

		String strs = "hello";

		buf.put(strs.getBytes());

		System.out.println(buf.position());

		System.out.println(buf.limit());

		System.out.println(buf.capacity());

		// start reading
		buf.flip();

		System.out.println("-----befor read--------");
		System.out.println(buf.position());

		System.out.println(buf.limit());

		System.out.println(buf.capacity());

		byte[] a = new byte[buf.limit()];
//		System.out.println(buf.get(a));
		System.out.println(new String(a));

		System.out.println("-----after read--------");
		System.out.println(buf.position());

		System.out.println(buf.limit());

		System.out.println(buf.capacity());

	}
}

class Demon {
	public static void main(String[] args) throws IOException {

		RandomAccessFile aFile = new RandomAccessFile("a.txt", "rw");

		FileChannel inChannel = aFile.getChannel();

		RandomAccessFile aFile1 = new RandomAccessFile("b.txt", "rw");

		FileChannel inChannel1 = aFile1.getChannel();

		// create buffer with capacity of 48 bytes
		ByteBuffer buf = ByteBuffer.allocate(4);

		for (; inChannel.read(buf) != -1;) {

//			inChannel1.write(buf);

			buf.flip(); // make buffer ready for read

			for (; buf.hasRemaining();) {
				inChannel1.write(buf);
			}

			buf.rewind();

			for (; buf.hasRemaining();) {
				System.out.print((char) buf.get()); // read 1 byte at a time
			}

			buf.clear(); // make buffer ready for writing

			System.out.println(buf);

		}

		aFile.close();
	}
}

class App2 {
	public static void main(String[] args) throws IOException {
		FileChannel channel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ, StandardOpenOption.WRITE);

		FileChannel channel1 = FileChannel.open(Paths.get("5.png"), StandardOpenOption.READ, StandardOpenOption.WRITE,
				StandardOpenOption.CREATE);

		MappedByteBuffer buf = channel.map(MapMode.READ_WRITE, 0, channel.size());

		MappedByteBuffer buf1 = channel1.map(MapMode.READ_WRITE, 0, channel.size());

		byte[] dst = new byte[buf.limit()];

		buf.get(dst);

		buf1.put(dst);

		channel.close();
		channel1.close();
	}
}

class C {
	public static void main(String[] args) throws IOException {
		List<String> lis = Files.readAllLines(Paths.get("a.txt"));

//		System.out.println(lis);

		for (String s : lis) {
			System.out.println(s);
		}
	}
}